const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const md5 = require('md5')
const userModel = require('../../models/userModel')

router.post('/login', async (req, res) => {
    try {
        let {username, password} = req.body
        const p = await userModel.findOne({username, password: md5(password)})
        if (p) {
            let token = jwt.sign({
                username: p.username,
                _id: p._id
            }, 'yuhongyu', {
                expiresIn: 60 * 60 * 24 * 7
            });

            //响应 token
            res.json({
                code: '0000',
                msg: '登录成功',
                data: token
            })

        } else {
            return res.json({
                code: '2002',
                msg: '用户名或密码错误~~~',
                data: null
            })
        }
        res.render('success', {msg: '登录成功', url: '/account'})
    } catch (err) {
        res.json({
            code: '2001',
            msg: '数据库读取失败~~~',
            data: null
        })
        return
    }

})
router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', {msg: '退出成功', url: '/login'})
    })
})
module.exports = router